# -*- coding: utf-8 -*-
'''
    :file: mails.py
    :author: -Farmer
    :url: https://blog.farmer233.top
    :date: 2021/05/24 11:32:11
'''
from flask import current_app
from flask.templating import render_template
from flask_mail import Message
from threading import Thread
from app.extensions import mail

def _send_async_mail(app, message):
    with app.app_context():
        mail.send(message)

def send_mail(subject, to, template, **kwargs):
    message = Message(
        subject = f"{current_app.config['MAIL_SUBJECT_PREFIX']} {subject}",
        recipients = [ to]
    )
    message.body = render_template(f'{template}.txt', **kwargs)
    message.html = render_template(f'{template}.html', **kwargs)
    app = current_app._get_current_object()
    thr = Thread(target=_send_async_mail, args=[app, message])
    thr.start()
    return thr

